<template>
  <div>
    <!-- 当点击 取消按钮 时，关闭弹窗 -->
    <el-drawer
      :title="title"
      :visible.sync="visible"
      size="75%"
      top="4vh"
      class="print-model"
      :append-to-body="true"
      @close="clearDialog()"
      v-loading="loding"
      :close-on-click-modal="false"
    >
      <div class="pack">
        <ele-form v-model="dialogfrom" v-bind="formConfig" ref="form">
        </ele-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="clearDialog()">{{
            $t("common.cancel")
          }}</el-button>
          <!-- <el-button
        type="primary"
        v-if="barcodeInfo.isCreateBarcode != 1"
        @click="creatBoxCode()"
        >生 成
      </el-button> -->
          <!-- <el-button type="danger" v-else @click="clearBoxcode()">清 除 </el-button> -->
          <el-button type="primary" @click="printBoxcode()">{{
            $t("common.print")
          }}</el-button>
        </div>
      </div>
    </el-drawer>
    <templateSelect
      ref="templateSelect"
      v-model="dialogfrom.barcodePrintTempCode"
      :searchData="{
        goodsCode: this.dialogfrom.prodCode,
        businessTypeCode: 'PRINT_MES_PC_MATERIAL_CARD',
      }"
      @select="
        (data) => {
          $set(dialogfrom, 'barcodePrintTemp', data.name);
        }
      "
    ></templateSelect>
  </div>
</template>

<script>
import { checkStr } from "@/utils/judge";
var valiNumberPass = (rule, value, callback) => {
  if (value === "" || value == undefined) {
    callback();
  } else if (isNaN(value)) {
    callback(new Error($i18n.t("afterReportWorkPrint.validate")));
  } else {
    callback();
  }
};
import templateSelect from "@/components/templateSelect/index.vue";

import {
  barcodePrintingList2,
  printTemplateInfo,
  mesProdBoxcode,
  baseCodeStrategy,
  getBoxCount,
  clearBoxcode,
  creatBoxCode, //生码
  printBarcode,
  getNextProcess,
  getQuantityById,
  printMaterial,
} from "@/api/barcodeprint/mesTrackingCardPrint";
import qs from "qs";
import BarcodePrint from "@/components/barcodePrint/barcodePrint";
import { setPrintData } from "@/utils/judge.js";
let arrBarcodePrintingList2 = [];
export default {
  name: "barcodePrintingAddModel",
  watch: {
    visible(val, oldVal) {
      if (!val) {
        this.$nextTick(() => {
          this.$refs.form.resetForm();
        });
        this.barcodeInfo = {};
      }
    },
    "dialogfrom.relaList": {
      handler: function (news, old) {
        this.$nextTick(() => {
          this.setQuantity();
        });
        // this.$nextTick(() => {
        //   this.setQuantity();
        // });
      },
      deep: true,
    },
  },
  props: {
    title: {
      type: String,
      default: "",
    },
  },
  components: { BarcodePrint, templateSelect },
  data() {
    let that = this;
    return {
      time: 1,
      loding: false,
      formConfig: {
        span: 24,
        isShowBackBtn: false,
        isShowSubmitBtn: false,
        labelPosition: "right",

        rules: {
          boxTotal: [
            { validator: valiNumberPass, trigger: ["change", "blur"] },
          ],
          boxNumber: [
            { validator: valiNumberPass, trigger: ["change", "blur"] },
          ],
          quantitys: [
            { validator: valiNumberPass, trigger: ["change", "blur"] },
          ],
          pieceWeight: [
            { validator: valiNumberPass, trigger: ["change", "blur"] },
          ],
          grossWeight: [
            { validator: valiNumberPass, trigger: ["change", "blur"] },
          ],
        },
        formDesc: {
          orderCode: {
            type: "input",
            label: $i18n.t("afterReportWorkPrint.workOrderCode"),
            layout: 8,
            required: true,
            disabled: true,
          },
          prodCode: {
            type: "input",
            label: $i18n.t("afterReportWorkPrint.code"),
            layout: 8,
            required: true,
            disabled: true,
          },
          prodName: {
            type: "input",
            label: $i18n.t("afterReportWorkPrint.name"),
            layout: 8,
            required: true,
            disabled: true,
          },
          lineName: {
            type: "input",
            label: $i18n.t("common.lineName"),
            layout: 8,
            // required: true,
            disabled: true,
          },
          productProcessName: {
            type: "input",
            label: $i18n.t("common.processName"),
            layout: 8,
            required: false,
            disabled: true,
          },
          // workCellName: {
          //   type: "input",
          //   label: $i18n.t("common.workCellName"),
          //   layout: 8,
          //   // required: true,
          //   disabled: true,
          // },
          //bing
          nextProcessName: {
            type: "input",
            label: $i18n.t("afterReportWorkPrint.nextProcessName"),
            layout: 8,
            // required: true,
            // disabled: true,
            required: false,
            disabled: false,
          },
          //接口返回字段为quantity  字段需要赋值其他 by bing
          // quantitys: {
          //   type: "input",
          //   label: $i18n.t("afterReportWorkPrint.quantity"),
          //   layout: 8,
          //   required: true,
          //   disabled: true,
          // },
          barcodePrintTemp: {
            type: "input",
            label: $i18n.t("afterReportWorkPrint.barcodePrintTemp"),
            layout: 8,
            disabled: () => {
              return this.barcodeInfo.isCreateBarcode == 1 ? true : false;
            },
            required: true,
            slots: {
              append(h) {
                return (
                  <el-button
                    icon="el-icon-search"
                    disabled={
                      that.barcodeInfo.isCreateBarcode == 1 ? true : false
                    }
                    onClick={() => {
                      that.$refs.templateSelect.show();
                    }}
                  ></el-button>
                );
              },
            },
          },
          // equipmentCode: {
          //   type: "input",
          //   label: $i18n.t("mesScanRecordDetail.equipmentName"),
          //   layout: 8,
          //   on: {
          //     change: (data, e) => {
          //       //that.$message.warning("条码模板,");
          //       that.handleChange(data);
          //     },
          //   },
          // },
          // operatorBy: {
          //   type: "input",
          //   label: $i18n.t("mesScanRecordDetail.operatorBy"),
          //   layout: 8,
          //   on: {
          //     change: (data, e) => {
          //       //that.$message.warning("条码模板,");
          //       that.handleChange(data);
          //     },
          //   },
          // },
          // prodCode: {
          //   type: "input",
          //   label: "产品编码",
          //   layout: 8,
          //   on: {
          //     change: (data, e) => {
          //       //that.$message.warning("条码模板,");
          //       that.handleChange(data);
          //     },
          //   },
          // },
          // prodName: {
          //   type: "input",
          //   label: "产品名称",
          //   layout: 8,
          //   on: {
          //     change: (data, e) => {
          //       //that.$message.warning("条码模板,");
          //       that.handleChange(data);
          //     },
          //   },
          // },
          // equipmentCode: {
          //   type: "input",
          //   label: $i18n.t("mesScanRecordDetail.equipmentCode"),
          //   layout: 8,
          //   on: {
          //     change: (data, e) => {
          //       //that.$message.warning("条码模板,");
          //       that.handleChange(data);
          //     },
          //   },
          // },
          // skGoodsCode: {
          //   type: "input",
          //   label: $i18n.t("mesScanRecordDetail.skGoodsCode"),
          //   layout: 8,
          //   //  required: true,
          //   // disabled: true,
          //   on: {
          //     change: (data, e) => {
          //       //that.$message.warning("条码模板,");
          //       that.handleChange(data)
          //     }
          //   }
          // },
          // materialChargeNumber: {
          //   type: "input",
          //   label: $i18n.t("mesScanRecordDetail.materialChargeNumber"),
          //   layout: 8,
          //   on: {
          //     change: (data, e) => {
          //       //that.$message.warning("条码模板,");
          //       that.handleChange(data);
          //     },
          //   },
          // },
          // pieceWeight: {
          //   type: "input",
          //   label: $i18n.t("mesScanRecordDetail.pieceWeight"),
          //   layout: 8,
          //   on: {
          //     change: (data, e) => {
          //       //that.$message.warning("条码模板,");
          //       that.handleChange(data);
          //     },
          //   },
          // },
          // grossWeight: {
          //   type: "input",
          //   label: $i18n.t("mesScanRecordDetail.grossWeight"),
          //   layout: 8,
          //   on: {
          //     change: (data, e) => {
          //       //that.$message.warning("条码模板,");
          //       that.handleChange(data);
          //     },
          //   },
          // },
          // finishDate: {
          //   type: "date",
          //   label: $i18n.t("mesScanRecordDetail.finishDate"),
          //   layout: 8,
          //   attrs: {
          //     valueFormat: "yyyy-MM-dd",
          //   },
          //   on: {
          //     change: (data, e) => {
          //       //that.$message.warning("条码模板,");
          //       that.handleChange(data);
          //     },
          //   },
          // },
          // boxNumber: {
          //   type: "input",
          //   label: $i18n.t("mesScanRecordDetail.boxNumber"),
          //   layout: 8,
          //   on: {
          //     change: (data, e) => {
          //       //that.$message.warning("条码模板,");
          //       that.handleChange(data);
          //     },
          //   },
          // },
          // boxTotal: {
          //   type: "input",
          //   label: $i18n.t("mesScanRecordDetail.boxTotal"),
          //   layout: 8,
          //   on: {
          //     change: (data, e) => {
          //       //that.$message.warning("条码模板,");
          //       that.handleChange(data);
          //     },
          //   },
          // },
          // transferBillNumber: {
          //   type: "input",
          //   label: $i18n.t("mesScanRecordDetail.transferBillNumber"),
          //   layout: 8,
          //   on: {
          //     change: (data, e) => {
          //       //that.$message.warning("条码模板,");
          //       that.handleChange(data);
          //     },
          //   },
          // },
          // inspectionResult: {
          //   type: "input",
          //   label: $i18n.t("mesScanRecordDetail.inspectionResult"),
          //   layout: 8,
          //   on: {
          //     change: (data, e) => {
          //       //that.$message.warning("条码模板,");
          //       that.handleChange(data);
          //     },
          //   },
          // },
          relaList: {
            label: $i18n.t("common.details"),
            layout: 24,
            required: true,
            type: "table-editor",
            attrs: {
              // 校检规则
              rules: {
                // lineNum: { required: true, message: "请输入行号" },
                // count: { required: true, message: $i18n.t('afterReportWorkPrint.inputQuantity') },
              },
              isShowAdd: false,
              // isShowDelete: false,
              // extraBtns: [
              //   {
              //     type: "删除",
              //   },
              // ],
              // 表格列
              //   字段已对完
              columns: [
                {
                  // el-table-column 的属性
                  type: "index",
                  width: 50,
                  label: $i18n.t("common.order"),
                  align: "center",
                },
                {
                  // el-table-column 的属性
                  prop: "workTeamCode",
                  label: $i18n.t("common.teamCode"),
                  minWidth: 100,
                  align: "center",
                },
                {
                  prop: "workTeamName",
                  label: $i18n.t("common.teamName"),
                  showOverflowTooltip: true,
                  minWidth: 100,
                  align: "center",
                },
                {
                  prop: "workShiftCode",
                  label: $i18n.t("common.shiftCode"),
                  showOverflowTooltip: true,
                  minWidth: 100,
                  align: "center",
                },
                {
                  prop: "workShiftName",
                  label: $i18n.t("common.shiftName"),
                  showOverflowTooltip: true,
                  minWidth: 100,
                  align: "center",
                },
                {
                  prop: "qualifiedQty",
                  label: $i18n.t("afterReportWorkPrint.qualifiedQty"),
                  showOverflowTooltip: true,
                  minWidth: 90,
                  align: "center",
                },
                {
                  prop: "printedQty",
                  label: $i18n.t("afterReportWorkPrint.printedQty"),
                  showOverflowTooltip: true,
                  minWidth: 90,
                  align: "center",
                },
                {
                  prop: "notPrintedQty",
                  label: $i18n.t("afterReportWorkPrint.notPrintedQty"),
                  showOverflowTooltip: true,
                  minWidth: 90,
                  align: "center",
                },
                {
                  prop: "quantity",
                  label: $i18n.t("afterReportWorkPrint.quantity"),
                  width: 140,
                  align: "center",
                  // fixed: "right",
                  // 当有 content 属性时, 可以指定相应的组件
                  content: {
                    // type 可以为全局注册的组件名或者组件引用
                    type: "el-input-number",
                    // attrs 是组件的属性
                    attrs: {
                      placeholder: $i18n.t("afterReportWorkPrint.inputQuantity"),
                      min: 1,
                      controlsPosition: "right",
                    },
                    on: {
                      change: (data, e) => {
                        //that.$message.warning("条码模板,");
                        that.handleChangeQuantity(data);
                      },
                    },
                  },
                },
                {
                  prop: "userName",
                  label: $i18n.t("afterReportWorkPrint.userName"),
                  showOverflowTooltip: true,
                  align: "center",
                },
                {
                  prop: "scanTime",
                  label: $i18n.t("afterReportWorkPrint.scanTime"),
                  showOverflowTooltip: true,
                  minWidth: 160,
                  align: "center",
                },

                // {
                //   fixed: "right",
                //   prop: "operate",
                //   label: "操作",
                //   content: {
                //     // type 可以为全局注册的组件名或者组件引用
                //     type: "el-button",
                //     label: "1111",
                //     attrs: {
                //       type: "danger",
                //       plain: true,
                //       size: "mini",
                //     },
                //     slots: {
                //       default(h, row) {
                //         return (
                //           <p
                //             on={{
                //               click: () => {
                //                 that.handleDelete(h, row);
                //               },
                //               input: () => {
                //                 debugger;
                //               },
                //             }}
                //           >
                //             删除
                //           </p>
                //         );
                //       },
                //     },
                //   },
                // },
              ],

              // 新行默认值
              newColumnValue: {
                // lineNum: 0,
                // quantity: 0,
              },
            },
          },
        },
      },
      barcodeInfo: {},
      dialogfrom: {},
      visible: false,
      loading: false,
      list: [],
      print: {
        id: "printArea3",
      },

      defList: [],
    };
  },

  methods: {
    //初始化
    async init(params) {
      console.log("params", params);
      this.defList = params;
      this.dialogfrom = { ...params[0], relaList: params };
      this.barcodeInfo = params[0];
      await this.getBoxCount();
      await this.getQuantityById();

      this.visible = true;
      this.$nextTick(() => {
        setTimeout(() => {
          this.handleChange(params[0].printTemp);
        }, 1000);
      });
    },

    async getBoxCount() {
      let res = await getNextProcess({
        ...this.dialogfrom,
        curProcessCode: this.dialogfrom.productProcessCode,
      });
      this.dialogfrom = {
        ...this.dialogfrom,
        ...res.data.result,
        quantitys: res.data.result.quantity,
      };
    },
    async getQuantityById() {
      let res = await getQuantityById(this.defList.map((ite) => ite.id));
      res.data.result.map((ite, i) => {
        this.dialogfrom.relaList[i].printedQty = ite.printedQty;
        this.dialogfrom.relaList[i].notPrintedQty = ite.notPrintedQty;

        // this.dialogfrom.relaList[i].quantity = ite.notPrintedQty;
        this.$set(
          this.dialogfrom.relaList[i],
          "quantity",
          ite.notPrintedQ || 1
        );
        this.defList[i].printedQty = ite.printedQty;
        this.defList[i].notPrintedQty = ite.notPrintedQty;
        this.defList[i].quantity = ite.notPrintedQty; //设置默认未打印数量
        // this.$set(
        //   this.formConfig.formDesc.relaList.attrs.columns[8].content.attrs,
        //   "max",
        //   ite.notPrintedQty
        // );
      });
      this.setQuantity();
    },
    // 计算表单总数量
    setQuantity() {
      this.$set(
        this.dialogfrom,
        "quantitys",
        (this.dialogfrom.quantity = this.dialogfrom.relaList.reduce(
          (prev, cur) => prev + cur.quantity,
          0
        ))
      );

      //console.log("12121", this.dialogfrom.quantity);
    },
    // 打印
    async printBoxcode() {
      this.$refs.form.validate().then(async (valid) => {
        let list = {
          ...this.dialogfrom,
          quantity: this.dialogfrom.quantitys,
          curProcessCode: this.dialogfrom.productProcessCode,
          curProcessName: this.dialogfrom.productProcessName,
          printtype: 0,
          relaList: this.dialogfrom.relaList.map((ite) => {
            return {
              scanRecordDetailId: ite.id,
              quantity: ite.quantity,
            };
          }),
        };
        // await printMaterial(list);
        this.visible = false;
        this.$parent.refresh();

        let { barcodePrintTempCode, barcodePrintTemp } = this.dialogfrom;
        setPrintData(
          {
            code: barcodePrintTempCode,
            name: barcodePrintTemp,
            materialPrintType: "1",
            status: "0",
          },
          [list]
        );
        this.$router.push("/splitPrint");
      });
    },
    async clearBoxcode() {
      try {
        let { value } = await this.$prompt($i18n.t('common.inputClearReason'), $i18n.t('common.tip'), {
          confirmButtonText: $i18n.t('common.ok'),
          cancelButtonText: $i18n.t('common.cancel'),
          inputValidator: (value) => {
            if (!value) {
              return $i18n.t('common.inputClearReason');
            }
          },
        });
        if (!value) {
          this.$message.warning($i18n.t("afterReportWorkPrint.pleaseEnterTheReasonForTheClearBoxCode"));
          return;
        }
        this.loding = true;
        let res = await clearBoxcode({
          clearReason: value,
          orderCode: this.dialogfrom.orderCode,
        });

        let deflt = this.dialogfrom.count;
        this.dialogfrom.count = 999;
        this.$nextTick(() => {
          this.dialogfrom.count = deflt;
          this.getBoxCount();
          this.$set(this.barcodeInfo, "isCreateBarcode", 0);
        });
      } finally {
        this.loding = false;
      }
    },
    handleChangeQuantity(data) {
      this.setQuantity();
      this.$set(this.barcodeInfo.values, "quantity", this.dialogfrom.quantitys);
    },
    //条码模板选择
    handleChange(e) {
      if (arrBarcodePrintingList2.length == 0) return;
      if (!this.dialogfrom.barcodePrintTemp) return;
      let obj = arrBarcodePrintingList2.find((ite) => {
        return e == ite.templateName;
      });
      if (!obj) return;
      this.loading = true;
      printTemplateInfo(obj.id)
        .then((res) => {
          this.time = new Date().getTime();
          this.barcodeInfo = {
            ...this.barcodeInfo,
            ...res.data.result,
            values: { ...this.dialogfrom, quantity: this.dialogfrom.quantitys },
          };
          // this.barcodeInfo.details.forEach(v => {
          //   v.componentHeight = '40'
          // })
        })
        .finally((res) => {
          this.loading = false;
        });
    },
    //修改容量
    countChange(e) {
      let quantity = Number(this.dialogfrom.quantity);
      let printQuantity = Math.ceil(quantity / e);
      this.dialogfrom.printQuantity = printQuantity;
    },
    //点击生码按钮
    creatBoxCode() {
      this.$refs.form.validate().then((valid) => {
        let {
          orderCode,
          count,
          barcodePrintTemp,
          boxCodeRule,
          printQuantity,
        } = this.dialogfrom;
        let data = {
          orderCode: orderCode, //'生产工单号',
          barcodePrintTemp: barcodePrintTemp, //'打印条码模板名称',
          boxCodeRule: boxCodeRule,
        };

        this.$confirm($i18n.t('afterReportWorkPrint.isCreatedTrackingCard'), $i18n.t('common.tip'), {
          confirmButtonText: $i18n.t('common.ok'),
          cancelButtonText: $i18n.t('common.cancel'),
          type: "warning",
        }).then(() => {
          this.loding = true;
          creatBoxCode(data)
            .then((res) => {
              if (res.data.success) {
                //  this.$refs.print.$refs.printing.$el.click();
                this.$message.success($i18n.t("afterReportWorkPrint.createSuccess"));
                let deflt = this.dialogfrom.count;
                this.dialogfrom.count = 999;
                this.dialogfrom.id = res.data.result;
                this.$nextTick(() => {
                  this.dialogfrom.count = deflt;
                  this.getBoxCount();
                  this.$set(this.barcodeInfo, "isCreateBarcode", 1);
                });
              }
              this.loding = false;
            })
            .catch((err) => {
              this.loding = false;
            });
        });
      });
    },

    clearDialog() {
      this.visible = false;
      this.$emit("refreshList");
    },
    //点击打印按钮
    handleRequest() {
      this.$refs.form.handleSubmitForm();
      this.$refs.form.validate().then((valid) => {
        let data = {
          isPrint: 0,
          orderCode: this.dialogfrom.orderCode, //'生产工单号',
        };
        mesProdBoxcode(data).then((res) => {
          if (res.data.success) {
            let list = res.data.result,
              info = this.barcodeInfo,
              infoList = [];
            if (Array.isArray(list) && list.length > 0) {
              list.forEach((item) => {
                infoList.push(item);
              });
            }
            delete info.values;
            info.values = infoList;
            localStorage.splitPrint = JSON.stringify(info);

            this.clearDialog();
            window.open("/mom/component/mes/splitPrint?type=1");
          }
        });
      });

      // barcodePrintingAdd(data)
      //   .then((res) => {
      //     if (res.data.success) {
      //       this.$refs.print.$refs.printing.$el.click();
      //     }
      //     this.$emit("refreshList");
      //   })
      //   .catch((err) => {
      //     console.log("查询失败", err);
      //   });
    },
  },
};
</script>

<style lang="scss" scoped>
.print-model {
  #printArea3 {
    position: relative;
  }

  .dis-none {
    display: none;
  }
  .pack {
    padding: 20px;
    padding-top: 0px;
  }
  .dialog-footer {
    padding-top: 20px;
    display: flex;
    justify-content: end;
  }
}
</style>
